﻿<%@ WebHandler Language="C#" Class="BrowseFilesManagerHandler" %>
//Description:文件管理器、Windows服务管理器
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Wangjh
//create Date:2023-02-13
using System;
using System.Web;
using System.Web.SessionState;
using BusinessRule.DTO;
using Newtonsoft.Json;
using System.IO;
using System.Collections.Generic;
using ICSharpCode.SharpZipLib.Zip;
using System.Data;
using System.ServiceProcess;

public class BrowseFilesManagerHandler : IHttpHandler, IRequiresSessionState
{
    
    public void ProcessRequest (HttpContext context) {
        try {
            var action = context.Request.Form["action"].ToString();
            switch (action)
            {
                case "showFilesByDir":
                    ShowFilesByDir(context);
                    break;
                case "downDirOrFiles":
                    DownDirOrFiles(context);
                    break;
                case "deleteDirAndFiles":
                    DeleteDirAndFiles(context);
                    break;
                case "getWindowsServiceList":
                    getWindowsServiceList(context);
                    break;
                case "stopService":
                    stopService(context);
                    break;
                case "startService":
                    startService(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult()
            {
                Result = false,
                Message = ex.Message
            };
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
    /// <summary>
    /// 启动指定服务
    /// add:wangjh 20241219
    /// </summary>
    public void startService(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        var serviceName = context.Request["serviceName"].ToString();//服务名称
        // 创建ServiceController实例
        ServiceController sc = new ServiceController(serviceName);
        if (sc.Status != ServiceControllerStatus.Running)
        {
            sc.Start();
            result.Message = "启动服务" + serviceName + "中……";

            // 等待服务达到运行状态
            sc.WaitForStatus(ServiceControllerStatus.Running);
            result.Message = "启动服务" + serviceName + "成功";
        }

        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 停止指定服务
    /// add:wangjh 20241219
    /// </summary>
    public void stopService(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        var serviceName = context.Request["serviceName"].ToString();//服务名称
        // 创建ServiceController实例
        ServiceController sc = new ServiceController(serviceName);
        if (sc.CanStop)
        {
            sc.Stop();
            result.Message = "停止服务" + serviceName + "中……";

            // 等待服务停止
            sc.WaitForStatus(ServiceControllerStatus.Stopped);
            result.Message = "停止服务" + serviceName + "成功";
        }
         
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取本机所有Windows Service服务信息
    /// add:wangjh 20241219
    /// </summary>
    public void getWindowsServiceList(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        ServiceController[] services = ServiceController.GetServices();
        List<Object> re = new List<Object>();
        foreach(ServiceController ser in services){
            re.Add(new {
                CanStop = ser.CanStop,
                Status = ser.Status,
                ServiceName = ser.ServiceName,
                ServiceType = ser.ServiceType,
                DisplayName = ser.DisplayName
            });
        }

        result.ReturnData = re;

        result.Message = "获取成功";
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="context"></param>
    public void DeleteDirAndFiles(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        var files = context.Request["dirOrFiles"].ToString();//路径及文件夹信息信息
        var topPath = context.Request["topPath"].ToString();//顶层路径

        DataTable dtFiles = JsonConvert.DeserializeObject<DataTable>(files);

        foreach (DataRow drFile in dtFiles.Rows)
        {
            if (drFile["type"].ToString() == "文件夹")
            {
                Directory.Delete(topPath + drFile["fileName"].ToString(), true);
            }
            else
            {
                File.Delete(topPath + drFile["fileName"].ToString());
            }
        }

        result.Message = "删除成功";
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    #region 展示文件
    /// <summary>
    /// 展示文件，根据路径
    /// </summary>
    /// <param name="context"></param>
    public void ShowFilesByDir(HttpContext context) {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;
        
        var returnData=new List<Dictionary<string,string>>();
        var fileItem = new Dictionary<string, string>() { { "fileName", "" }, { "lastChangeDate", "" }, 
        { "type", "" }, { "size", "" } };
        
        var topPath = context.Request["topPath"].ToString();//顶层路径 eg:topPath=C:\Program Files (x86)\Camstar\InSite Web Application\InSiteWebApplication\forms\Custom
        DirectoryInfo mydir = new DirectoryInfo(topPath);
        if (!mydir.Exists )
        {
            result.Message = "未找到此顶层路径";         
            result.Result = false;
            context.Response.Write(JsonConvert.SerializeObject(result));
        }

        foreach (DirectoryInfo dr in mydir.GetDirectories())
        {
            fileItem = new Dictionary<string, string>() { { "fileName", "" }, { "lastChangeDate", "" }, 
            { "type", "" }, { "size", "" } };
            
            fileItem["fileName"] = dr.Name;
            fileItem["lastChangeDate"] = dr.LastWriteTime.ToString ("yyy/MM/dd HH:mm");
            fileItem["type"] = "文件夹";
            fileItem["size"] = "";

            returnData.Add(fileItem );
        }

        foreach (FileInfo fi in mydir.GetFiles())
        {
            fileItem = new Dictionary<string, string>() { { "fileName", "" }, { "lastChangeDate", "" }, 
            { "type", "" }, { "size", "" } };
            
            fileItem["fileName"] = fi.Name;
            fileItem["lastChangeDate"] = fi.LastWriteTime.ToString("yyy/MM/dd HH:mm"); 
            fileItem["type"] = fi.Extension;
            fileItem["size"] = Math.Ceiling (fi.Length/1024.0).ToString ();

            returnData.Add(fileItem);
        }
        result.ReturnData = returnData;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    #endregion

    /// <summary>
    /// 下载文件夹/文件
    /// </summary>
    /// <param name="context"></param>
    public void DownDirOrFiles(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        var files = context.Request["dirOrFiles"].ToString();//路径及文件夹信息信息
        var topPath = context.Request["topPath"].ToString();//顶层路径
        
        DataTable dtFiles = JsonConvert.DeserializeObject<DataTable>(files );

        var downDir = HttpContext.Current.Server.MapPath("~" + "/Temp2/代码导出");//结果路径
        //清除结果文件夹的数据
        var targetDir = new DirectoryInfo(downDir);
        if (!targetDir.Exists)
        {
            result.Message = "未找到 " + targetDir .FullName + " 路径";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        foreach (DirectoryInfo dr in targetDir.GetDirectories())
        {
            dr.Delete(true);
        }
        foreach (FileInfo fi in targetDir.GetFiles())
        {
            fi.Delete();
        }
         
        //处理文件或文件夹信息到指定目录底下
        foreach (DataRow drFile in dtFiles.Rows) {
            if (drFile["type"].ToString() == "文件夹")
            {
                var _downDir = downDir;
                if (!Directory.Exists(_downDir + "\\" + drFile["fileName"].ToString()))
                {
                    Directory.CreateDirectory(_downDir + "\\" + drFile["fileName"].ToString());
                    _downDir = _downDir + "\\" + drFile["fileName"].ToString();
                }
                
                var resultPathList = new List<string>();
                FilterFilesByDate(new DirectoryInfo(topPath + drFile["fileName"].ToString()), "", _downDir, new List<string> { "*" },
                    new DateTime(1970, 1, 1, 0, 0, 0, 0),ref resultPathList);
            }
            else {
                File.Copy(topPath + drFile["fileName"].ToString(), downDir+"\\"+ drFile["fileName"].ToString(), true);
            }
        }
        
        //压缩文件，压缩到InSiteWebApplication\Temp2
        var zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
        var zipFilName = "/Temp2/" + "代码导出" + (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds.ToString() + ".zip";
        zip.CreateZip(HttpContext.Current.Server.MapPath("~" + zipFilName), downDir, true, "");
        
        result.Message = "下载完成";
        result.ReturnData = zipFilName;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 筛选文件到指定路径，有递归
    /// </summary>
    /// <param name="sourcePath"></param>
    /// <param name="targetPath"></param>
    /// <param name="startDate"></param>
    void FilterFilesByDate(DirectoryInfo sourceDir, string sonPathItem, string targetPath, List<string> fileFormat, DateTime startDate, ref List<string> resultPath, Boolean firstDir = false)
    {
        foreach (FileInfo fi in sourceDir.GetFiles())
        {
            if ((fileFormat.Contains(fi.Extension.Replace(".", "")) || fileFormat.Contains("*")) && fi.LastWriteTime >= startDate)
            {
                if (!Directory.Exists(targetPath + sonPathItem))
                {
                    Directory.CreateDirectory(targetPath + sonPathItem);
                }
                File.Copy(fi.FullName, targetPath + sonPathItem + "\\" + fi.Name, true);
                resultPath.Add(targetPath + sonPathItem + "\\" + fi.Name);
            }
        }
        if (firstDir)
            return;
        foreach (DirectoryInfo dr in sourceDir.GetDirectories())
        {
            string sonDirName = dr.FullName.Replace(sourceDir.FullName, "");
            FilterFilesByDate(dr, sonPathItem + sonDirName, targetPath, fileFormat, startDate, ref resultPath);
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}